//
//  AppDelegate.m
//  JuBoCRM
//
//  Created by 马宁 on 2022/6/13.
//  Copyright © 2022年 iningKe. All rights reserved.
//

#import "AppDelegate.h"
#import "WRNavigationBar.h"

#import <UMShare/UMShare.h>
#import <UMCommon/UMCommon.h>
#import <UMCommon/UMConfigure.h>
#import <UMPush/UMessage.h>

//#import <AdSupport/AdSupport.h>
//#import <AppTrackingTransparency/AppTrackingTransparency.h>

#import <WXApi.h>

#import <UserNotifications/UserNotifications.h>

//#import <BaiduMapAPI_Base/BMKBaseComponent.h>
//#import <BMKLocationkit/BMKLocationComponent.h>

#import "XiaoXiTongZhiViewController.h"
#import "ShenPiXiaoXiViewController.h"

#import "GetLocFile.h"

@interface AppDelegate ()<WXApiDelegate,UNUserNotificationCenterDelegate>

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.window.backgroundColor = [UIColor whiteColor];
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
    
    
    [self setNavBarAppearence];
    
    [self welcomePage];
    
    [self.window makeKeyAndVisible];
    
    // U-Share 平台设置
    
    [self configUSharePlatforms];
    
    [WXApi registerApp:@"wx457a1f9f972acfda" universalLink:@"https://help.wechat.com/sdksample/"];
    
//    [self idfa];
    
    // Push组件基本功能配置
    UMessageRegisterEntity* entity =[[UMessageRegisterEntity alloc] init];
    //type是对推送的几个参数的选择，可以选择一个或者多个。默认是三个全部打开，即：声音，弹窗，角标
        entity.types =UMessageAuthorizationOptionBadge|UMessageAuthorizationOptionSound|UMessageAuthorizationOptionAlert;
    [UNUserNotificationCenter currentNotificationCenter].delegate=self;
    [UMessage registerForRemoteNotificationsWithLaunchOptions:launchOptions Entity:entity     completionHandler:^(BOOL granted,NSError*_Nullable error){
        if(granted){
        }else{
        }
    }];
    
    return YES;
}

////个性化广告
//- (NSString*)idfa {
//    __block NSString *idfa = @"";
//    ASIdentifierManager *manager = [ASIdentifierManager sharedManager];
//    if (@available(iOS 14, *)) {
//        [ATTrackingManager requestTrackingAuthorizationWithCompletionHandler:^(ATTrackingManagerAuthorizationStatus status) {
//            if (status == ATTrackingManagerAuthorizationStatusAuthorized) {
//                idfa = [[manager advertisingIdentifier] UUIDString];
//            }
//        }];
//    }else{
//        if ([manager isAdvertisingTrackingEnabled]) {
//            idfa = [[manager advertisingIdentifier] UUIDString];
//        }
//    }
//    return idfa;
//}



- (void)configUSharePlatforms
{

    [UMConfigure initWithAppkey:@"65e67117a769754556d9a300" channel:@""];
    /* 设置微信的appKey和appSecret */
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_WechatSession appKey:@"wx457a1f9f972acfda" appSecret:@"0762ea3f99094ffdbc2ee4f5bfb164b4" redirectURL:@"http://mobile.umeng.com/social"];
  
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_QQ appKey:@"1105828391"/*设置QQ平台的appID*/  appSecret:nil redirectURL:@"http://mobile.umeng.com/social"];
    [UMSocialGlobal shareInstance].universalLinkDic = @{@(UMSocialPlatformType_WechatSession):@"https://www.baidu.com/.well-known/apple-app-site-association/", @(UMSocialPlatformType_QQ):@"https://www.baidu.com/.well-known/apple-app-site-association/" };
    
    
 
    
}


+ (instancetype)shareInstance {
    return (AppDelegate *) [UIApplication sharedApplication].delegate;
}
- (void)welcomePage {
    if(isLogin){
        GXtabbarController *tabBarCtn=[[GXtabbarController alloc]init];
        self.tabBarController = tabBarCtn;
        self.window.rootViewController = tabBarCtn;
    }else{
        LoginViewController *login = [[LoginViewController alloc] init];
        GXBaseNavController *nav = [[GXBaseNavController alloc]initWithRootViewController:login];
        self.window.rootViewController = nav;
    }
}

- (void)setNavBarAppearence
{
    
    
    // 设置是 广泛使用WRNavigationBar，还是局部使用WRNavigationBar，目前默认是广泛使用
    [WRNavigationBar wr_widely];
    [WRNavigationBar wr_setBlacklist:@[@"TZImagePickerController",
                                       @"TZGifPhotoPreviewController",
                                       @"TZAlbumPickerController",
                                       @"TZPhotoPreviewController",
                                       @"TZVideoPlayerController"]];
    
    // 设置导航栏默认的背景颜色
    [WRNavigationBar wr_setDefaultNavBarBarTintColor:[UIColor clearColor]];
    // 设置导航栏所有按钮的默认颜色
    [WRNavigationBar wr_setDefaultNavBarTintColor:[UIColor whiteColor]];
    // 设置导航栏标题默认颜色
    [WRNavigationBar wr_setDefaultNavBarTitleColor:[UIColor whiteColor]];
    // 统一设置状态栏样式
    [WRNavigationBar wr_setDefaultStatusBarStyle:UIStatusBarStyleLightContent];
    // 如果需要设置导航栏底部分割线隐藏，可以在这里统一设置
    [WRNavigationBar wr_setDefaultNavBarShadowImageHidden:YES];
}
/// 在这里写支持的旋转方向，为了防止横屏方向，应用启动时候界面变为横屏模式
- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window {
    // 可以这么写
    if (self.shouldChangeOrientation) {
        if(self.isFullScreenPlay){
            return UIInterfaceOrientationMaskAllButUpsideDown;
        }
        UIDevice *device = [UIDevice currentDevice];
        if(device.orientation==UIDeviceOrientationLandscapeLeft){
            return UIInterfaceOrientationMaskLandscapeRight;
        }else if(device.orientation==UIDeviceOrientationLandscapeRight)
        {
            return UIInterfaceOrientationMaskLandscapeRight;

        }else{
            return UIInterfaceOrientationMaskLandscapeRight;
        }
    }
    return UIInterfaceOrientationMaskPortrait;
}

//iOS10新增：处理前台收到通知的代理方法
-(void)userNotificationCenter:(UNUserNotificationCenter*)center willPresentNotification:(UNNotification*)notification withCompletionHandler:(void(^)(UNNotificationPresentationOptions))completionHandler{
    NSDictionary* userInfo = notification.request.content.userInfo;
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]){
    [UMessage setAutoAlert:NO];
    //必须加这句代码
    [UMessage didReceiveRemoteNotification:userInfo];

    }else{
    //应用处于前台时的本地推送接受
    }
    completionHandler(UNNotificationPresentationOptionSound|UNNotificationPresentationOptionBadge|UNNotificationPresentationOptionAlert);
}

//iOS10新增：处理后台点击通知的代理方法
-(void)userNotificationCenter:(UNUserNotificationCenter*)center didReceiveNotificationResponse:(UNNotificationResponse*)response withCompletionHandler:(void(^)(void))completionHandler{
    NSDictionary* userInfo = response.notification.request.content.userInfo;
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]){
    //必须加这句代码
    [UMessage didReceiveRemoteNotification:userInfo];
    }else{
    //应用处于后台时的本地推送接受
    }
    NSLog(@"收到推送消息：%@",userInfo);
    
    
    
    ShenPiXiaoXiViewController *xiangQing = [[ShenPiXiaoXiViewController alloc] init];
    xiangQing.hidesBottomBarWhenPushed = YES;
    self.tabBarController.selectedViewController.hidesBottomBarWhenPushed = YES;
    [self.tabBarController.selectedViewController pushViewController:xiangQing animated:YES];
    
//    if ([GetHandleString(userInfo, @"messageType") integerValue] == 1) {
//        if ([GetHandleString(userInfo, @"instanceId") length] > 0) {
//            [self toGongDanDetail:GetHandleString(userInfo, @"instanceId")];
//        }
//    }else if ([GetHandleString(userInfo, @"messageType") integerValue] == 2) {
//        //        审查记录
//        HeTongShenHeJiLuViewController *xiangQing = [[HeTongShenHeJiLuViewController alloc] init];
//        xiangQing.hidesBottomBarWhenPushed = YES;
//        self.tabBarController.selectedViewController.hidesBottomBarWhenPushed = YES;
//        [self.tabBarController.selectedViewController pushViewController:xiangQing animated:YES];
//        
//        [self yiDuXiaoXiWithIndex:userInfo];
//        
//    }else if ([GetHandleString(userInfo, @"messageType") integerValue] == 3) {
//        //        文书生成记录
//        ZhuanXieJiLuViewController *xiangQing = [[ZhuanXieJiLuViewController alloc] init];
//        xiangQing.hidesBottomBarWhenPushed = YES;
//        self.tabBarController.selectedViewController.hidesBottomBarWhenPushed = YES;
//        [self.tabBarController.selectedViewController pushViewController:xiangQing animated:YES];
//        
//        [self yiDuXiaoXiWithIndex:userInfo];
//    }else if ([GetHandleString(userInfo, @"messageType") integerValue] == 4 || [GetHandleString(userInfo, @"messageType") integerValue] == 5 || [GetHandleString(userInfo, @"messageType") integerValue] == 6) {
//        //       邀请记录
////        YaoQingJiLuViewController *xiangQing = [[YaoQingJiLuViewController alloc] init];
//        XiTongXiaoXiViewController *xiangQing = [[XiTongXiaoXiViewController alloc] init];
//        xiangQing.hidesBottomBarWhenPushed = YES;
//        self.tabBarController.selectedViewController.hidesBottomBarWhenPushed = YES;
//        [self.tabBarController.selectedViewController pushViewController:xiangQing animated:YES];
////        [self yiDuXiaoXiWithIndex:userInfo];
//    }
    
}

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    
    const unsigned *tokenBytes = (const unsigned *)[deviceToken bytes];
    NSString *deviceTokenString = [NSString stringWithFormat:@"%08x%08x%08x%08x%08x%08x%08x%08x",
                                    ntohl(tokenBytes[0]), ntohl(tokenBytes[1]), ntohl(tokenBytes[2]),
                                    ntohl(tokenBytes[3]), ntohl(tokenBytes[4]), ntohl(tokenBytes[5]),
                                    ntohl(tokenBytes[6]), ntohl(tokenBytes[7])];
    
    // Print the device token
    NSLog(@"Device Token: %@", deviceTokenString);
    
    
    [UMessage registerDeviceToken:deviceToken];

    [ZZPUtils saveUserDefultsData:deviceTokenString forKey:@"deviceTokenString"];
    if(userIsLogin){
        [self baoCunToken];
    }

}

//新增或更新用户标识
- (void)baoCunToken{
    if([[ZZPUtils readUserDefultsDataForKey:@"deviceTokenString"] length] > 0){
        NSMutableDictionary *paraDic = [NSMutableDictionary dictionary];
        [paraDic setValue:@"2" forKey:@"deviceType"];
        [paraDic setValue:[ZZPUtils readUserDefultsDataForKey:@"deviceTokenString"] forKey:@"deviceToken"];
        [[ZZPRequest getWebUtil] postJsonNetworkRequestURLString:@"/adminUmeng/deviceToken" andParas:paraDic andShowHud:NO andTransferGottenData:^(id info, NSError *error) {
            if (!error) {
                NSLog(@"info:%@",info);
            }
        }];
    }
}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error API_AVAILABLE(ios(3.0)){
    
}
- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}







@end
